package graduation.project.mutant.strategy;

import graduation.project.body.Expression;
import graduation.project.body.Mutants;
import graduation.project.body.OriginExpression;
import graduation.project.exception.NonExpressionException;

import java.util.ArrayList;

public class TNFMutantsGen implements MutantsGenerator {

	public Mutants generateMutants(String expression, int mutantsNum) {
		
		try{
			OriginExpression originEx = new OriginExpression(expression);
			return generateMutants(originEx, mutantsNum);
		}catch(NonExpressionException e){
			System.out.println("TNFMutantsGen: the expression is invalid.");
			e.printStackTrace();
		}
		return null;
	}

	public Mutants generateMutants(OriginExpression originEx, int num) {
		
		Mutants result = new Mutants(originEx.getExpression(), "TNF");
		ArrayList<Expression> mutantSet = new ArrayList<Expression>();
		String idnf = originEx.getIDNF();
		
		int count = 0;
		
		StringBuffer exp = new StringBuffer();
		exp.append(idnf);
		int termCount = idnf.split("\\+").length;
		int beginPos;
		int endPos = -1;
		
		String subString;
		for(int i = 0; i < termCount; i++){
			beginPos = endPos;
			endPos = idnf.indexOf("+", beginPos + 1);
			if(endPos < 0)
				endPos = idnf.length();
			subString = exp.substring(beginPos + 1, endPos);
			exp.delete(beginPos + 1, endPos).insert(beginPos + 1, "!(" + subString + ")");
			try {
				mutantSet.add(new Expression(exp.toString()));
			} catch (NonExpressionException e) {
				System.out.println("TNFMutantsGen: the expression is invalid.");
				e.printStackTrace();
			}
			exp.delete(beginPos + 1, endPos + 3).insert(beginPos + 1, subString);
			if(num != -1 && ++count >= num)
				break;
		}
		
		result.setMutants(mutantSet);
		return result;
	}

}
